package com.yfbao.horizon.schedule.tk.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Component
public class HashService {

    @Autowired
    private RedisTemplate redisTemplate;

    private static String hashKey="hashKey";

    public void bathPutHash(){
        Map<String,Long> map =new HashMap<>();
        Random random =new Random();
        for(int i=0;i<100;i++){
            map.put("num-"+i,System.currentTimeMillis()+random.nextInt(500));

        }
        redisTemplate.opsForHash().putAll(hashKey,map);
    }

    public void scanHash(){
        ScanOptions options = ScanOptions.scanOptions().match("*").count(10).build();

        Cursor<Map.Entry<String, Long>> cursor = null;
        try {
            cursor   = redisTemplate.opsForHash().scan(hashKey, options);

            while (cursor.hasNext()) {
                Map.Entry<String, Long> entry = cursor.next();
                Object field = entry.getKey();
                Object value = entry.getValue();

                // 根据需要处理字段和值
                System.out.println("字段: " + field + ", 值: " + value);
            }

        }finally {
            if(cursor!=null){
                try {
                    cursor.close();
                }catch (Exception e){
                }
            }

        }


    }
}
